//============================================================================
// Name        : HttpDataInput.cpp
// Author      : Christian Barth
// Version     :
// Copyright   : MIT
// Description :
//============================================================================

#include "HttpDataInput.h"

#include <curl/curl.h>

#include <istream>
#include <ostream>
#include <fstream>
#include <sstream>
#include <iostream>

using namespace std;
using namespace faz_broker;

static string theUrl ("http://www.faz.net/d/login/show.aspx?type=boersens");
static string depotUrl ("http://boersenspiel.faz.net/a/spiel.cgi");
static string cookieFile ("fazCookie.fc");

HttpDataInput::HttpDataInput(const string& usr, const string& pwd)
: msUsername (usr), msPassword (pwd)
{
  curl_global_init(CURL_GLOBAL_ALL);
}

HttpDataInput::~HttpDataInput()
{
  curl_global_cleanup();
}

Stock
HttpDataInput::GetStock(const std::string& name) const
{
  // initialize a new handle
  CURL *easyhandle = curl_easy_init();

  // setting the url as option to the handle
  curl_easy_setopt(easyhandle, CURLOPT_URL, theUrl.c_str());
  curl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);

  FILE *out;
  out=fopen ("output.html", "w");
  curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, out);

  // setting the post data for the form
  string formData ("usr_login");
  formData.append(msUsername.c_str());
  formData.append("&usr_pwd=");
  formData.append(msPassword);
  formData.append("&x=14&y=13&usr_autologin=on");
  curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, formData.c_str());

  // setting a cookie file
  curl_easy_setopt(easyhandle, CURLOPT_COOKIESESSION, 1);
  curl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, cookieFile.c_str());

  // perform the handle
  curl_easy_perform(easyhandle);

  fclose(out);
  out = fopen ("output_depot.html", "w");

  curl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, cookieFile.c_str());

  // getting the depot page
  curl_easy_setopt(easyhandle, CURLOPT_URL, depotUrl.c_str());

  // perform the handle
  curl_easy_perform(easyhandle);

  fclose (out);
  // clean up the curl handle
  curl_easy_cleanup(easyhandle);


  Stock stock("fake stock", 10, 12.30, 43.20);
  return stock;
}

vector<Stock>
HttpDataInput::GetStocks() const
{
  vector<Stock> v;
  return v;
}
